/*
 * FNISVGEditor - JavaScript - based editor for SVG graphics 
 * Copyright (C) 2008 - 2009 Antti Leppä / Foyt
 * http://www.foyt.fi
 * 
 * License: 
 * 
 * Licensed under GNU Lesser General Public License Version 2.1 or later (the "LGPL") 
 * http://www.gnu.org/licenses/lgpl.html
 */
FNISVGEditorUndoManager = Class.create( {
  initialize : function(editorInstance) {
    this._editorInstance = editorInstance;
    this._events = new Array();
    this._nextEventIndex = -1;
  },
  undo : function() {
    if (this.hasUndoableEvents()) {
      var event = this._events[this._nextEventIndex];
      
      this._nextEventIndex--;
      var controller = GetFNISVGEditorUndoEventControllerVault().getControllerFor(event);
      controller.undo(this._editorInstance, event);
      
      this.fire("statusChanged", {
        action: 'undo',
        event: event,
        hasUndoableEvents: this.hasUndoableEvents(),
        hasRedoableEvents: this.hasRedoableEvents()
      });
    }
  },
  redo : function() {
    if (this.hasRedoableEvents()) {
      this._nextEventIndex++;
      var event = this._events[this._nextEventIndex];
      var controller = GetFNISVGEditorUndoEventControllerVault().getControllerFor(event);
      controller.redo(this._editorInstance, event);
      
      this.fire("statusChanged", {
        action: 'redo',
        event: event,
        hasUndoableEvents: this.hasUndoableEvents(),
        hasRedoableEvents: this.hasRedoableEvents()
      });
    }
  },
  hasUndoableEvents : function() {
    return this._nextEventIndex >= 0;
  },
  hasRedoableEvents : function() {
    return this._nextEventIndex < (this._events.length - 1);
  },
  addUndoableEvent : function(event) {
    if (this._nextEventIndex > -1)
      this._events.splice(this._nextEventIndex + 1, this._events.length - (this._nextEventIndex + 1));
    
    this._events.push(event);
    this._nextEventIndex = this._events.length - 1;
    this.fire("statusChanged", {
      action: 'eventAdded',
      event: event,
      hasUndoableEvents: this.hasUndoableEvents(),
      hasRedoableEvents: this.hasRedoableEvents()
    });
  },
  clearStack: function () {
    this._nextEventIndex = -1;
    while (this._events.length > 0)
      this._events.pop();
    
    this.fire("statusChanged", {
      action: 'stackCleared',
      hasUndoableEvents: false,
      hasRedoableEvents: false
    });
  }  
});

Object.extend(FNISVGEditorUndoManager.prototype, fni.events.FNIEventSupport);